/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: Executor.java 657 2007-06-29 07:07:01Z jacek.kolezynski $
 */
package logmatcher.executor;

import bsh.EvalError;
import bsh.Interpreter;

import logmatcher.report.ReportEvent;
import logmatcher.report.ReportHandler;

import logmatcher.utils.Config;
import logmatcher.utils.TimestampGenerator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;

import java.util.Arrays;
import java.util.concurrent.CountDownLatch;


/**
 *  This class takes care of executing all test cases. It can execute test cases one by one, waiting for one task
 *  to finish before starting another task. Until one task is finished the current thread is blocked.
 */
public class Executor {
    //~ Static fields/initializers -------------------------------------------------------------------------------------

    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(Executor.class);

    /** End of test log message. */
    static final String END_OF_TEST = "--- END OF TEST ---";

    //~ Instance fields ------------------------------------------------------------------------------------------------

    /** CountDownLatch used to block the runTest method until all tasks have finished. */
    private CountDownLatch ctd;

    /** Report handle of the test suite. */
    private ReportHandler reportHandler;

    /** TODO: DOCUMENT ME! */
    private String testSuiteName = "";

    /** TODO: DOCUMENT ME! */
    private String testCaseName = "";

    /** TODO: DOCUMENT ME! */
    private String outputDir;
    
    private int numberOfTasks = 2;

    //~ Methods --------------------------------------------------------------------------------------------------------

    /**
     *  DOCUMENT ME!
     *
     *  @return TODO: DOCUMENT ME!
     *
     *  @todo DOCUMENT ME!
     */
    public ReportHandler getReportHandler() {
        return reportHandler;
    }


    /**
     *  
    DOCUMENT ME!
     *
     *  @return TODO: DOCUMENT ME!
     *
     *  @todo DOCUMENT ME!
     */
    public String getTestCaseName() {
        return testCaseName;
    }


    /**
     *  
    DOCUMENT ME!
     *
     *  @return TODO: DOCUMENT ME!
     *
     *  @todo DOCUMENT ME!
     */
    public String getTestSuiteName() {
        return testSuiteName;
    }


    /**
     *  Starts test case by running a test case beanshell script.
     *
     *  @param interpreter the interpreter
     *  @param source the beanshell script
     *
     *  @throws FileNotFoundException if beanshell script not found
     *  @throws IOException if something goes wrong while opening the script
     *  @throws EvalError if something goes wrong while evaluating the script
     */
    public void runTest(Interpreter interpreter, String source)
        throws FileNotFoundException, IOException, EvalError {
    	
        reportHandler.receiveEvent(
                new ReportEvent(ReportEvent.Type.TEST_STARTED, source));
        interpreter.source(source);
        ctd = new CountDownLatch(numberOfTasks);
        if(LOGGER.isDebugEnabled())
          LOGGER.debug("Starting test "+source+" "+TimestampGenerator.getTimestamp());

        try {
            ctd.await();
        } catch (InterruptedException e) {
            LOGGER.error("Error while waiting for tasks to end", e);
        }

        LOGGER.info("All tasks are ended");
        LOGGER.info(END_OF_TEST);

        if (outputDir == null) {
            outputDir = Config.LOG_OUTPUT_DIRECTORY + File.separator + TimestampGenerator.getTimestamp("yyyy-MM-dd")
                + File.separator + testSuiteName;
        }
        
        reportHandler.receiveEvent(
                new ReportEvent(ReportEvent.Type.TEST_ENDED, source, new Integer(numberOfTasks)));

        String outputFile = testCaseName + "_" + TimestampGenerator.getTimestamp("yyyy-MM-dd-HH-mm-ss");
        LogSweeper.sweepToZip(Config.LOG_TMP_DIRECTORY, ".log", outputDir, outputFile, true);
        
        if(LOGGER.isDebugEnabled())
            LOGGER.debug("Test finished, end time = "+TimestampGenerator.getTimestamp());

    }


    /**
     *  @todo DOCUMENT ME!
     */
    public void finishSuite() {
        LOGGER.debug("finishSuite called");

        File srcdir = new File(Config.LOG_TMP_DIRECTORY);

        FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    if (name.startsWith("report") && name.endsWith("txt")) {
                        return true;
                    }

                    return false;
                }
            };

        if (srcdir.exists()) {
            File[] reportFiles = srcdir.listFiles(filter);
            
            if(reportFiles!=null)
            	if (reportFiles.length >= 1) {
            		LOGGER.warn("More than one report files is present in the directory. Last one will be moved.");
            	}
            else{
            	LOGGER.debug("There are no report files found");
            	return;
            }

            Arrays.sort(reportFiles);

            File tmpReportFile = reportFiles[reportFiles.length - 1];

            if (tmpReportFile.exists()) {
                File reportFile = new File(
                        outputDir + File.separator + testSuiteName + "_"
                        + TimestampGenerator.getTimestamp("yyyy-MM-dd-HH-mm-ss") + ".report");
                boolean res = tmpReportFile.renameTo(reportFile);

                if (res) {
                    LOGGER.debug("Report file renamed successfuly");
                } else {
                    LOGGER.debug("Could not rename report file");
                }
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Report file " + tmpReportFile.getAbsoluteFile() + " does not exist ");
                }
            }
        }
    }


    /**
     *  DOCUMENT ME!
     *
     *  @param reportHandler TODO: DOCUMENT ME!
     *
     *  @todo DOCUMENT ME!
     */
    public void setReportHandler(ReportHandler reportHandler) {
        this.reportHandler = reportHandler;
    }


    /**
     *  
    DOCUMENT ME!
     *
     *  @param testCaseName TODO: DOCUMENT ME!
     *
     *  @todo DOCUMENT ME!
     */
    public void setTestCaseName(String testCaseName) {
        this.testCaseName = testCaseName;
    }


    /**
     *  
    DOCUMENT ME!
     *
     *  @param testSuiteName TODO: DOCUMENT ME!
     *
     *  @todo DOCUMENT ME!
     */
    public void setTestSuiteName(String testSuiteName) {
        this.testSuiteName = testSuiteName;
    }


    /**
     *  Informs that a task has been ended.
     */
    public void taskEnded() {
        LOGGER.info("One of the tasks is ended");
        ctd.countDown();
    }


	public int getNumberOfTasks() {
		return numberOfTasks;
	}


	public void setNumberOfTasks(int numberOfTasks) {
		this.numberOfTasks = numberOfTasks;
	}
}
